package model

import (
	_ "github.com/go-sql-driver/mysql"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"publish/model"
)

func InitDB() {
	sql := beego.AppConfig.String("mysql")
	orm.RegisterDriver("mysql", orm.DRMySQL)
	orm.RegisterDataBase("default", "mysql", sql)
	orm.RegisterModel(new(AllRead),new(AutoTask),new(Account),new(model.PubTask),new(AccountArticle),new(Article))
	orm.RunSyncdb("default", false, true)
}

type Account struct {
	Id int `orm:"column(id)" json:"id"`
	NickName string `orm:"column(nick_name)" json:"nick_name"`
	Username string `orm:"column(username)" json:"username"`
	Password string `orm:"column(password)" json:"password"`
	Cookie string `orm:"column(cookie);type(text)" json:"cookie"`
	Plat string `orm:"column(plat)" json:"plat"`
	PlatParams string `orm:"column(plat_params)" json:"plat_params"`
	Status int `orm:"column(status)" json:"status"`  // 0 未检查 1 通过 2 失效
}

func (a *Account) GetCookie() string{
	return a.Cookie
}


func AddAccount(account *Account) error{
	orm := orm.NewOrm()
	_,err := orm.Insert(account)
	return err
}


func UpdateAccount(account Account) error{
	orm := orm.NewOrm()
	_,err := orm.Update(&account,"status")
	return err
}

func UpdateCookie(account Account) error{
	beego.Info("更新Cookie：",account.Id,account.Cookie)
	orm := orm.NewOrm()
	_,err := orm.Update(&account,"cookie")
	return err
}

func ListAccount()  ([]Account,error){
	o := orm.NewOrm()
	accounts :=  []Account{}
	s := "select * from account"
	_,err := o.Raw(s).QueryRows(&accounts)
	return accounts,err
}

func ListAccountByPage(page int,size int)  (accounts []Account,count int,err error){
	o := orm.NewOrm()
	s := "select * from account order by id asc limit ?,?"
	_,err = o.Raw(s, (page-1)*size, size).QueryRows(&accounts)
	if err != nil{
		return nil,0,err
	}
	sql := `select count(*) from account`
	err = o.Raw(sql).QueryRow(&count)
	if err != nil{
		return nil,0,err
	}
	return accounts,count,err
}

func DeleteAccount(id int) error{
	o := orm.NewOrm()
	if _,err := o.Delete(&Account{Id:id},"id");err != nil{
		return err
	}
	return nil
}

func GetAccountById(id int) (*Account,error){
	o := orm.NewOrm()
	account := &Account{Id:id}
	if err := o.Read(account,"id");err != nil{
		return nil,err
	}
	return account,nil
}